package com.wx.util;

import java.io.IOException;
import java.util.TreeMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;

import com.wx.entity.WechatTemplateMsg;
import com.wx.menu.Button;
import com.wx.menu.Menu;
import com.wx.menu.ViewButton;

@SuppressWarnings("deprecation")
public class WeiXinUtil {
	private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=ACCESS_TOKEN";
	private static final String APPID = "wxbd55b37a512c0a82";
	private static final String APPSECRET = "7010980753c541725f356f96db31a33e";
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	
	private static final String SEND_TEMPLATE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
														
	/**
	 * 编写Get请求的方法。但没有参数传递的时候，可以使用Get请求
	 * 
	 * @param url
	 *            需要请求的URL
	 * @return 将请求URL后返回的数据，转为JSON格式，并return
	 */
	public static JSONObject doGetStr(String url) throws ClientProtocolException, IOException {
		DefaultHttpClient client = new DefaultHttpClient();// 获取DefaultHttpClient请求
		HttpGet httpGet = new HttpGet(url);// HttpGet将使用Get方式发送请求URL
		JSONObject jsonObject = null;
		HttpResponse response = client.execute(httpGet);// 使用HttpResponse接收client执行httpGet的结果
		HttpEntity entity = response.getEntity();// 从response中获取结果，类型为HttpEntity
		if (entity != null) {
			String result = EntityUtils.toString(entity, "UTF-8");// HttpEntity转为字符串类型
			jsonObject = JSONObject.fromObject(result);// 字符串类型转为JSON类型
		}
		return jsonObject;
	}

	/**
	 * 编写Post请求的方法。当我们需要参数传递的时候，可以使用Post请求
	 * 
	 * @param url
	 *            需要请求的URL
	 * @param outStr
	 *            需要传递的参数
	 * @return 将请求URL后返回的数据，转为JSON格式，并return
	 */
	public static JSONObject doPostStr(String url, String outStr) throws ClientProtocolException, IOException {
		DefaultHttpClient client = new DefaultHttpClient();// 获取DefaultHttpClient请求
		HttpPost httpost = new HttpPost(url);// HttpPost将使用Get方式发送请求URL
		JSONObject jsonObject = null;
		httpost.setEntity(new StringEntity(outStr, "UTF-8"));// 使用setEntity方法，将我们传进来的参数放入请求中
		HttpResponse response = client.execute(httpost);// 使用HttpResponse接收client执行httpost的结果
		String result = EntityUtils.toString(response.getEntity(), "UTF-8");// HttpEntity转为字符串类型
		jsonObject = JSONObject.fromObject(result);// 字符串类型转为JSON类型
		return jsonObject;
	}

	/**
	 * 获取AccessToken
	 * 
	 * @return 返回拿到的access_token及有效期
	 */
	public static AccessToken getAccessToken() throws ClientProtocolException, IOException {
		AccessToken token = new AccessToken();
		String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);// 将URL中的两个参数替换掉
		JSONObject jsonObject = doGetStr(url);// 使用刚刚写的doGet方法接收结果
		if (jsonObject != null) { // 如果返回不为空，将返回结果封装进AccessToken实体类
			token.setToken(jsonObject.getString("access_token"));// 取出access_token
			token.setExpiresIn(jsonObject.getInt("expires_in"));// 取出access_token的有效期
		}
		return token;
	}

	/**
	 * 发送模版消息
	 * @param wechatTemplateMsg
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String sendTemplateMsg(WechatTemplateMsg wechatTemplateMsg) throws ClientProtocolException, IOException {
		AccessToken token = getAccessToken();
		String data = JSONObject.fromObject(wechatTemplateMsg).toString();
		String url = SEND_TEMPLATE_MESSAGE.replace("ACCESS_TOKEN", token.getToken());
//		System.out.println(data);
//		System.out.println(url);
//		System.out.println(token.getToken());
		JSONObject jsonObject = doPostStr(url, data);
		String result = "SUCCESS";
		if (jsonObject != null) {
			return "errcode:" + jsonObject.getInt("errcode") + " errmsg:" +jsonObject.getString("errmsg");
		}
		return result;
	}
	
	/**
	 * 初始化车牌模版消息
	 * 模版ID：JJiECzJdHviKcmbpHEsq590g0kymyLYhRKZEpVp5O6g
	 * 
	 * @param username
	 * @param carnum
	 * @param time
	 * @param openid
	 * @return
	 */
	public static String initCarTemplateMsg(String username, String carnum, String time, String openid) {
		String result = null;
		WechatTemplateMsg wts = new WechatTemplateMsg();
		TreeMap<String, TreeMap<String, String>> tm = new TreeMap<>();
		tm.put("first", WechatTemplateMsg.item("车牌记录通知", "#173177"));
		tm.put("keyword1", WechatTemplateMsg.item(username, "#173177"));
		tm.put("keyword2", WechatTemplateMsg.item(carnum, "#173177"));
		tm.put("keyword3", WechatTemplateMsg.item(time, "#173177"));
		tm.put("remark", WechatTemplateMsg.item("谢谢使用本系统，祝你一路平安！", "#173177"));
		wts.setData(tm);
		wts.setTouser(openid);
		wts.setTemplate_id("JJiECzJdHviKcmbpHEsq590g0kymyLYhRKZEpVp5O6g");
		wts.setUrl("");
		try {
			WeiXinUtil.sendTemplateMsg(wts);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 用户注册提醒模版
	 * 模版ID:ygQt3Hhf2mCJKsW09dkEZcpe5aWWhPRatvfR8GMboPg
	 * 
	 * @param username
	 * @param tel
	 * @param openid
	 * @return
	 */
	public static String initUserTemplateMsg(String username, String tel, String openid, String content) {
		String result = null;
		WechatTemplateMsg wts = new WechatTemplateMsg();
		TreeMap<String, TreeMap<String, String>> tm = new TreeMap<>();
		tm.put("first", WechatTemplateMsg.item(content, "#173177"));
		tm.put("keyword1", WechatTemplateMsg.item(username, "#173177"));
		tm.put("keyword2", WechatTemplateMsg.item(tel, "#173177"));
		tm.put("remark", WechatTemplateMsg.item("谢谢使用本系统，祝你一路平安！", "#173177"));
		wts.setData(tm);
		wts.setTouser(openid);
		wts.setTemplate_id("ygQt3Hhf2mCJKsW09dkEZcpe5aWWhPRatvfR8GMboPg");
		wts.setUrl("");
		try {
			WeiXinUtil.sendTemplateMsg(wts);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 组装菜单
	 * 
	 * @return
	 */
	public static Menu initMenu() {
		Menu menu = new Menu();
		// ClickButton button11 = new ClickButton();
		// button11.setName("项目介绍");
		// button11.setType("click");
		// button11.setKey("1");
		//
		// ClickButton button12 = new ClickButton();
		// button12.setName("成员介绍");
		// button12.setType("click");
		// button12.setKey("2");

		ViewButton button21 = new ViewButton();
		button21.setType("view");
		button21.setName("查看已有注册用户");
		button21.setUrl("userlist.jsp");

		ViewButton button22 = new ViewButton();
		button22.setType("view");
		button22.setName("用户注册");
		button22.setUrl("login.jsp");

		// Button button1 = new Button();
		// button1.setName("项目简介");
		// button1.setSub_button(new Button[] { button11, button12 });

		Button button2 = new Button();
		button2.setName("用户管理");
		button2.setSub_button(new Button[] { button21, button22 });

		menu.setButton(new Button[] { button2 });
		return menu;
	}

	public static int createMenu(String token, String menu) throws ClientProtocolException, IOException {
		int result = 0;
		String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doPostStr(url, menu);
		if (jsonObject != null) {
			result = jsonObject.getInt("errcode");
		}
		return result;
	}
}
